@inject('storeService', 'App\App\Services\StorageService')
@inject('VoteCandidate', 'App\Models\VoteCandidate\VoteCandidate')

@php
	if(empty($activity->rule)){
		$basic="{}";
		$specs="[]";
		$specs_isopen = 0;
	}else{
		$rule = json_decode($activity->rule,true);
		if (empty($rule['basic'])){
			 $basic="{}";
		}else{
			$basic = json_encode($rule['basic']);
		}
		if (empty($rule['spec'])){
			 $specs="[]";
			 $specs_isopen = 0;
		}else{
			$specs =$rule['spec']['isopen']==1? (isset($rule['spec']['list'])?$rule['spec']['list']:[]):[];
			$specs_isopen = $rule['spec']['isopen'];
			foreach ($specs as $key=> &$item){
				$item['id'] = $key;
			}
			unset($item);
			$specs = json_encode($specs);
		}

	}
	if (!empty($activity->shares)){
		$share = $activity->shares;
		$shareArray = json_decode($share,true);
		$shareArray['isopen'] = isset($shareArray['isopen'])?$shareArray['isopen']:0;
		$shareArray['thumb'] = isset($shareArray['thumb'])?$shareArray['thumb']:'';
		$shareArray['qrcode'] = isset($shareArray['qrcode'])?$shareArray['qrcode']:'';
	}else{
		$shareArray = ['landindPage'=>0,'isopen'=>0,'thumb'=>'','qrcode'=>''];
		$share = json_encode($shareArray);
	}
@endphp
<style>

	/*投票*/
	ul.vote-group-card {
		border-radius: 4px;
		background-color: rgba(221, 221, 221, 0.5);
		padding-top: 22px !important;
		padding-bottom: 15px !important;
		padding-right: 18px !important;
		padding-left: 18px !important;
	}

	.competition-option-card, .vote-group-card {
		list-style: none;
	}

	.vote-column-smimg {
		max-width: 179px;
		max-height: 117px;
	}

	.vote-view-smimg {
		max-width: 320px;
		max-height: 240px;
	}
	.vote-view-smimg img.img-responsive{
		max-height:100%;
	}
	.row .control-label img,.form-group .control-label video,.form-group .control-label audio{
		max-width: 100% !important;
	}
	.vote-column-smimg img{
		height: 50px;
	}
	.mce-edit-area *{
		color: #000 !important;
	}
	.mce-content-body{
		color: #000 !important;
	}
	.bootbox .modal-dialog{width:auto;min-height:50px;height:auto}.bootbox .modal-dialog *{font-size:14px}.bootbox .modal-header,.bootbox .modal-body,.bootbox .modal-footer{border:0}.bootbox .modal-footer .btn{padding:4px 16px}.bootbox .modal-header .close{margin-top:-5px}.bootbox .modal-header button{font-size:21px}.bootbox.bootbox-confirm .modal-dialog{width:350px;margin:20% auto}.checks{font-size:13px;color:#fb404b;text-align:center;padding-top:20px;width:373px;margin:0 auto}.checks i{color:#fb404b}
</style>
<link rel="stylesheet" href="/css/CSS/main.css"/>
{{--<link rel="stylesheet" href="/css/admin/activityDemo.css"/>--}}

<div class="text-left">
	<ul class="nav nav-icons" role="tablist">
		<li class="active">
			<a href="#activity_tab_0" role="tab" data-toggle="tab" aria-expanded="true">
				内容设置
			</a>
		</li>
		{{--<li>--}}
		{{--<a href="#activity_tab_3" role="tab" data-toggle="tab" aria-expanded="true">--}}
		{{--自定义设置--}}
		{{--</a>--}}
		{{--</li>--}}

		@if($ativity_template->template != 'poll' && $ativity_template->template != 'ballot')
			<li>
				<a href="#activity_tab_1" role="tab" data-toggle="tab" aria-expanded="true">
					分组设置
				</a>
			</li>
		@endif

		<li id="voteSet">
			<a href="#activity_tab_2" role="tab" data-toggle="tab" aria-expanded="true">
				投票项设置
			</a>
		</li>
		<li>
			<a href="#activity_tab_3" role="tab" data-toggle="tab" aria-expanded="true">
				渠道配置
			</a>
		</li>
		<li>
			<a href="#activity_tab_4" role="tab" data-toggle="tab" aria-expanded="true">
				列表配置
			</a>
		</li>
	</ul>
</div>
<div class="tab-content">
	<div class="tab-pane active" id="activity_tab_0">
		<div class="card">
			<div class="content">
				<div class="form-group">
					<label class="col-md-2 control-label">活动名称</label>
					<input type="hidden" name='activity_demoid' value="" id="activity_demoid"/>
					<div class="col-md-7">
						<input type="hidden" name="action" value="vote"/>
						<input class="form-control" type="text" ng-model="activity.name"
							   name="name" data-msg="请输入活动名称"
						/>
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-2 control-label">活动时间</label>
					<div class="col-md-7">
						<div class="row service-charges">

							<div class="col-md-5 service-charges-name service-charges-name-0"
								 style="padding-left: 15px;">
								<input type="text" placeholder="开始时间" name="startTime" data-msg="请输入开始时间"
									   value="{{$activity->startTime}}" class="form-control datetimepicker">
							</div>
							<div class="col-md-5 service-charges-remark service-charges-remark-0">
								<input type="text" placeholder="结束时间" data-msg="请输入结束时间" name="endTime"
									   value="{{$activity->endTime}}" class="form-control datetimepicker">
							</div>

						</div>
					</div>
				</div>
				@php
					if(!empty($activity->limit)){
						$limit = json_decode($activity->limit,true);
					}else{
						$limit = [
							'num'=>1,
							'type'=>\App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE,
							'votes'=>1
						];
					}
				@endphp
				<div class="form-group">
					<label class="col-md-2 control-label">活动次数</label>
					<div class="col-md-7">
						<div class="row service-charges">
							<label class="control-label pull-left" style="padding-left: 15px;">每人可参与</label>
							<div class="col-md-9 input-group">
								<input type="number" placeholder="参与次数" value="{{$limit['num']}}" name="limit[num]"
									   min="1" data-msg="请输入参与次数" class="form-control">
								<div class="input-group-addon">
									<select name="limit[type]" id="" class="">
										<option value="{{\App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE}}"
												@if($limit['type'] == \App\Models\Activity\Activity::ACTIVITY_LIMIT_DAY_TYPE) selected @endif >
											次/每日
										</option>
										<option value="{{\App\Models\Activity\Activity::ACTIVITY_LIMIT_ALL_TYPE}}"
												@if($limit['type'] == \App\Models\Activity\Activity::ACTIVITY_LIMIT_ALL_TYPE) selected @endif>
											次/活动全程
										</option>
									</select>
								</div>
							</div>
						</div>
						@if($ativity_template->template == 'multiple-vote')
						<div class="row service-charges">
							<label class="control-label pull-left" style="padding-left: 15px;">每次最多投</label>
							<div class="col-md-3">
								<input value="{{$limit['votes']}}" class="form-control" type="number"
									   name="limit[votes]" data-msg="请输票数"/>
							</div>
							<label class="control-label pull-left">票</label>
						</div>
						@endif
					</div>
				</div>

				<div class="form-group backgroundImg-container" style="display: none;">
					<label class="col-md-2 control-label">更换背景</label>
					<div class="col-md-7">
						<input type="file" name="upfile" accept="image/gif,image/jpeg,image/png"
							   data-target="uploadImageFile" data-for="backgroundImg" data-preview-file-type="text"
							   class="form-control" value="" title="">
						<input type="hidden" ng-model="activity.previewData.background" name="backgroundImg"
							   data-preview="{{$storeService->tomedia($activity->backgroundImg)}}"
							   value="{{$activity->backgroundImg}}">
						<span class="help-block">支持PNG、JPG格式，小于200KB</span>
					</div>
				</div>
				<div class="form-group backgroundColor-container" style="display: none;">
					<label class="col-md-2 control-label">背景颜色</label>
					<div class="col-md-7 input-group colorPicker colorpicker-component" data-format="alias">

						<input type="text" value="{{$activity->backgroundColor}}" name="backgroundColor"
							   class="form-control"/>
						<span class="input-group-addon"><i></i></span>
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-2 control-label">活动备注信息</label>
					<div class="col-md-7">
						<textarea class="form-control"
								  name="description">{{$activity->description}}</textarea>
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-2 control-label">活动规则</label>
					<div class="col-md-7">
						<textarea class="form-control tinymceEditor"
								  name="description">{{$activity->description}}</textarea>
					</div>
				</div>
				{{--<div class="form-group">--}}
					{{--<label class="col-md-2 control-label">活动规则</label>--}}
					{{--<div class="col-md-7">--}}
						{{--<textarea class="form-control tinymceEditor"--}}
								  {{--name="ruleDescription">{{$activity->ruleDescription}}</textarea>--}}
					{{--</div>--}}
				{{--</div>--}}
			</div>
		</div>
	</div>
	<div class="tab-pane" id="activity_tab_1">
		<div class="card">
			<div class="content">
				<div>
					<h5 class="" style="float: left;margin-right: 10px;">
						<input type="hidden" name="groupIsOpen" ng-model="activity.groupIsOpen" id="groupIsOpen">
						开启分组
					</h5>
					{{--bootstrap-switch vote[group][open] data-ischecked="@{{activity.vote_group_isopen}}"--}}
					<div class=".switch" id="switch-vote-group" style="margin-top: 5px;"
						 data-on-label="<i class='fa fa-check'></i>"
						 data-off-label="<i class='fa fa-times'></i>" data-on-color="success">
						<input type="checkbox">
					</div>
				</div>
				<div class="div-vote-group" style="display: none">
					<div class="row">
						<div class="col-sm-12 col-md-12">
							<ul class="vote-group-card col-sm-10 col-md-10 col-md-offset-1">

								@if(empty($activity->groupIsopen))
									{{--<li class="card vote-group-form" data-index=0>--}}
									{{--<div class="content">--}}
									{{--<div class="row">--}}
									{{--<div class="col-md-12 col-sm-12">--}}
									{{--<img src="/images/admin/delet_red.png"--}}
									{{--class="vote_group_card_delet pull-right mgb10 mgr30">--}}
									{{--</div>--}}
									{{--<div class="form-group">--}}
									{{--<label class="col-md-2 control-label">分组名称</label>--}}
									{{--<div class="col-md-7">--}}
									{{--<input class="form-control" type="text" name="group[][name]"--}}
									{{--placeholder="请输入分组名称" data-msg="请输入分组名称"/>--}}
									{{--</div>--}}
									{{--</div>--}}
									{{--</div>--}}
									{{--</div>--}}
									{{--</li>--}}
								@else
									<li class="card vote-group-form" ng-repeat="group in activity.group"
										data-index="@{{group.index}}" data-groupid="@{{group.group_id}}">
										<div class="content">
											<div class="row">
												<div class="col-md-12 col-sm-12">
													<img src="/images/admin/delet_red.png"
														 class="vote_group_card_delet pull-right mgb10 mgr30">
												</div>

												<div class="form-group">
													<label class="col-md-2 control-label">分组名称</label>
													<div class="col-md-7">
														<input class="form-control" type="text" value="@{{group.title}}"
															   placeholder="请输入分组名称" name="group[][name]"
															   data-msg="请输入分组名称"/>
													</div>
												</div>

											</div>
										</div>
									</li>
								@endif

								<div class="pull-right mgud add-vote-group">
									<button type="button"
											class="btn btn-info add-vote-group-butten"
									>
										+添加分组
									</button>
								</div>
							</ul>
						</div>
					</div>
					<div class="row">
						<div class="col-sm-10 col-md-10 col-md-offset-1">
							<div class="pull-center mgud save-vote-group">
								<button type="button"
										class="btn btn-info btn-fill save-vote-group-butten"
								>
									保存
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="tab-pane" id="activity_tab_2">
		<div class="card">

			<ul id="myTab" class="nav nav-tabs" style="padding-left: 15px;padding-top: 30px;">
				<li class="active"><a href="#vote" data-toggle="tab">自定义投票项</a>
				</li>
				<li><a href="#enroll" data-toggle="tab">关联报名添加投票项</a></li>
			</ul>

			<div class="content table-responsive tab-content">

				<div class="tab-pane fade in active" id="vote">
					<div class="toolbar">
						<a href="javascript:;" class="btn btn-success add-vote-btn">
							<i class="fa fa-plus"></i> 添加投票项
						</a>
					</div>
					<table id="bootstrap-vote-table-container" class="table"
						   data-url="/web/vote/candidate?activity_id={{$activity->id}}">
						<thead>
						<th data-field="select" data-checkbox="true">选择</th>
						<th data-field="cover_url" data-formatter="codeFormatter" data-sortable="true">投票编号</th>
						<th data-field="cover_url" data-formatter="imgFormatter" class="vote-column-smimg"
							data-sortable="false">投票内容
						</th>
						<th data-field="title" data-sortable="false">名称</th>
						@if($ativity_template->template != 'poll' && $ativity_template->template != 'ballot')
							<th data-field="group_title" data-sortable="true">组名</th>
						@endif
						<th data-field="weight" data-sortable="true">权重</th>
						<th data-field="status" data-sortable="false" data-formatter="statusFormatter">状态</th>
						<th data-field="actions" class="td-actions text-center" data-events="operateEvents"
							data-formatter="operateFormatter">操作
						</th>
						</thead>
						<tbody>
						</tbody>
					</table>
					<div class="footer">
						<a href="javascript:;" id="allCheck" class="btn btn-fill btn-round btn-xs btn-warning">批量删除</a>
					</div>
				</div>

				<div class="tab-pane fade" id="enroll">
					<div class="form-group">
						<span class="col-md-3 col-sm-3 control-label" style="text-align: center">是否关联报名活动</span>
						<div class="col-md-1 col-sm-1">
							<div class="switch" id="switch-vote-enroll" style="margin-top: 5px;"
								 data-on-label="<i class='fa fa-check'></i>"
								 data-off-label="<i class='fa fa-times'></i>" data-on-color="success">
								<input type="checkbox" name="rule[relevanceEnrollOn]">
							</div>
						</div>
						<span class="col-md-7 col-sm-7 control-label" style="text-align: left;margin-left: 20px;">注：关联的报名活动，填充投票项</span>

					</div>
					<div class="div-vote-enroll" style="display: none">
						<div class="form-group">
							<div class="col-md-7 col-sm-7 pl28">
								<span class="help-block">*请选择需要关联的报名活动</span>
								<select class="form-control" name="rule[relevanceEnroll]" id="relevanceEnroll">
									<option value ="volvo">选择需关联的报名活动</option>
								</select>
							</div>
						</div>
					</div>
				</div>

			</div>

		</div>
	</div>
	{{--<link rel="stylesheet" href="/css/CSS/main.css"/>--}}
	<div class="tab-pane" id="activity_tab_3">
		<div class="card">
			<div class="content">
				<div class="form-group">
					<label class="col-md-2 control-label">发布到APP</label>
					<div class="col-md-7">
						<div class="switch has-switch" id="switch-enroll-app" data-on-label="是"
							 data-off-label="否" data-on-color="success" style="margin-top:6px;">
							<div class="switch-animate"
								 ng-class="{'switch-on':channel.app.is_open=='on', 'switch-off': channel.app.is_open=='off'}">
								<span class="switch-left" ng-click="channel.app.is_open='off'">是</span>
								<label ng-click="channel.app.is_open=='off'?channel.app.is_open='on':channel.app.is_open='off'">&nbsp;</label>
								<span class="switch-right" ng-click="channel.app.is_open='on'">否</span>
							</div>
							<input type="hidden" name="app[is_open]" ng-value="channel.app.is_open" ng-model="channel.app.is_open"/>
						</div>
					</div>
				</div>
				<div class="form-group app" ng-if="channel.app.is_open=='on'">
					<label class="col-md-2 control-label">APP下载链接</label>
					<div class="col-md-7">
						<input class="form-control app_url" type="text" name="app[app_urls][0]"
							   placeholder="配置app下载链接" ng-model="channel.app.app_urls[0]"/>
					</div>
				</div>
				<div class="form-group app">
					<label class="col-md-2 control-label">发布到微信</label>
					<div class="col-md-7">
						<div class="switch has-switch" id="switch-enroll-wechat" data-on-label="是"
							 data-off-label="否" data-on-color="success" style="margin-top:6px;">
							<div class="switch-animate"
								 ng-class="{'switch-on':channel.wechat.is_open=='on', 'switch-off': channel.wechat.is_open=='off'}">
								<span class="switch-left" ng-click="toggleClass($event,'off')">是</span>
								<label ng-click="toggleClass($event,'label')">&nbsp;</label>
								<span class="switch-right" ng-click="toggleClass($event,'on')">否</span>
							</div>
						</div>
						<input type="hidden" name="wechat[is_open]" ng-value="channel.wechat.is_open" ng-model="channel.wechat.is_open"/>
					</div>
				</div>
				<div class="form-group wechat" ng-if="channel.wechat.is_open=='on'">
					<div class="form-group backgroundImg-container">
						<label class="col-md-2 control-label">上传二维码</label>
						<div class="file-wrap col-md-7">
							<input ng-model="channel.wechat.qr_code[0]" class="fileInput ngFileInput" refresh="refresh"
								   file-config="fileConfig" type="file" multiple="multiple" name="upfile"
								   accept="image/gif,image/jpeg,image/png"
								   data-target="uploadImageFiles" data-preview-file-type="text" value="" title="">
							<span class="help-block mb0">支持PNG、JPG格式，小于200KB</span>
						</div>
						<input type="hidden" name="wechat[qr_code][0]" ng-value="channel.wechat.qr_code[0]" ng- ng-model="channel.wechat.qr_code[0]"/>
					</div>
				</div>
				<hr/>
				<div class="form-group">
					<label class="col-md-2 control-label">开启分享</label>
					<div class="col-md-7">
						<div class="switch" id="switch-enroll-share" data-on-label="是" data-off-label="否"
							 data-on-color="success" style="margin-top:6px;">
							<input type="checkbox" name="share[isopen]">
						</div>
					</div>
				</div>
				<div class="div-enroll-self" style="display: none">
					<div class="form-group">
						<label class="col-md-2 control-label">分享标题</label>
						<div class="col-md-7">
							<input class="form-control input-enroll-self-title" type="text" maxlength="15"
								   name="share[title]" placeholder="最多15个字" data-msg="最多只能输入15个字符"
							/>
						</div>
					</div>
					<div class="form-group">
						<label class="col-md-2 control-label">分享文案</label>
						<div class="col-md-7">
                                <textarea class="form-control input-enroll-self-inf" rows="5" maxlength="50"
										  name="share[content]" placeholder="最多50个字" data-msg="最多只能输入50个字符"
								></textarea>
						</div>
					</div>
					<div class="form-group backgroundImg-container">
						<label class="col-md-2 control-label">分享图片</label>
						<div class="col-md-7">
							<input type="file" name="upfile" accept="image/gif,image/jpeg,image/png"
								   data-target="uploadImageFile" data-for="share[thumb]" data-preview-file-type="text"
								   class="form-control" value="" title="">
							<input type="hidden" ng-model="activity.shares.thumb" name="share[thumb]"
								   data-preview="{{$storeService->tomedia($shareArray['thumb'])}}"
								   value="{{$shareArray['thumb']}}">
							<span class="help-block">支持PNG、JPG格式，小于200KB</span>
						</div>
					</div>
				</div>
			</div>
			{{--<div class="footer  pull-center">--}}
				{{--<button type="button" class="btn btn-info btn-fill btn-wd"--}}
						{{--ng-click="onFinishConfig()">保存--}}
				{{--</button>--}}
				{{--<div class="clearfix"></div>--}}
			{{--</div>--}}
		</div>
	</div>
	<div class="tab-pane" id="activity_tab_4">
		<div class="card">
			<div class="content">
				<div class="form-group">
					<label class="col-md-10 control-label col-md-offset-1" style="text-align: left">*列表配置仅限使用列表模式使用，如不需要使用列表模式请忽略此设置。</label>
				</div>
				<div class="form-group list-sm-images">
					<label class="col-md-2 control-label">列表缩略图</label>
					<div class="col-md-7">
						<input type="file" name="upfile" accept="image/gif,image/jpeg,image/png"
							   data-target="uploadImageFile" data-for="listBackgroundImg" data-preview-file-type="text"
							   class="form-control" value="" title="">
						<input type="hidden" name="listBackgroundImg"
							   data-preview="{{$storeService->tomedia($activity->listBackgroundImg)}}"
							   value="{{$activity->listBackgroundImg}}">
						<span class="help-block">支持PNG、JPG格式，小于200KB</span>
					</div>
				</div>
				{{--<div class="form-group">--}}
					{{--<label class="col-md-2 control-label">app下载链接</label>--}}
					{{--<div class="col-md-7">--}}
						{{--<input class="form-control input-enroll-self-appurl" type="text" name="app_url" value="{{$activity->app_url}}"  placeholder="配置app下载链接"/>--}}
					{{--</div>--}}
				{{--</div>--}}
			</div>
		</div>
	</div>
</div>
<script src="/js/admin/initUploadImageSize.js"></script>
<script type="text/javascript">

    //    initUploadImageFile();
    initUploadImageSize('.backgroundImg-container');
    //    initUploadMulImageFile();
    initTinymce();
    initDatetimepicker();
    initDatetimepicker('#vote_act_time');
    initTimepicker();
    initColorPickerAndSwitch();

    window.groupData = [];
    window.activity_demoid = '';

    require(['angular', 'directives'], function (angular) {
        var app = angular.module('app', ['directives','ngPlugin']);
        app.controller('subscriptionModalController',['$scope','$timeout','$http','$modalInstance','notify','items',function ($scope,$timeout,$http,$modalInstance,notify,items) {
            var profile = JSON.parse($('meta[name="profile"]').attr('content'));
            if(items.isAuthorize==1){
                $scope.postData = items.authorize;
            }else{
                $scope.postData = {
                    app_id: '',
                    app_secret: '',
                    group_code: profile.group_code,
                }
            }
            $scope.ok = function ($event) {
                if(!$scope.postData.app_id){
                    notify('APP_ID不能为空', 3);
                    return;
                }
                if(!$scope.postData.app_secret){
                    notify('SecurityKey不能为空', 3);
                    return;
                }
                var $btn = angular.element($event.target).addClass('disabled');
                $http({
                    method:items.isAuthorize==1?'PATCH':'POST',
                    url: '/web-api/configurations/wechat',
                    headers: JSON.parse($('meta[name="profile"]').attr('content')),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: $scope.postData,
                }).success(function (data) {
                    $btn.removeClass('disabled');
                    if (data.code == 200) {
                        if(items.isAuthorize==0){
                            notify('授权成功', 2);
                        }else{
                            notify('修改成功', 2);
                        }
                        $modalInstance.close($scope.postData);
                    } else {
                        notify(data.message, 3);
                    }
                }).error(function (data) {
                    $btn.removeClass('disabled');
                    notify(data.message, 3);
                });
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }]);
        app.controller('ActivityController', ['$scope', '$compile', '$timeout','$http','ngModal', function ($scope, $compile, $timeout,$http,ngModal) {
            // ================================================
            function GetRequest() {
                var url = location.search; //获取url中"?"符后的字串
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    strs = str.split("&");
                    for(var i = 0; i < strs.length; i ++) {
                        theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            }
            $scope.params = GetRequest();
            $scope.activity_id =  $scope.params.id;
            //图片上传配置
            $scope.fileConfig = {
                config: {
                    language: 'zh',
                    maxFileCount: 1,
                    maxFileSize: 200,
                },
            }
            $scope.channel = {
                app: {
                    is_open: 'off',
                    app_urls: []
                },
                wechat: {
                    is_open: 'off',
                    qr_code: []
                }
            }
            $scope.isAuthorize = -1;//是否授权
            $scope.authorize = {};//授权信息
            function requestAuthorize(){
                $http({
                    method:'get',
                    url: '/web-api/configurations/wechat',
                    headers: JSON.parse($('meta[name="profile"]').attr('content')),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                }).success(function (data) {
                    if (data.code == 200) {
                        if(data.data&&data.data['app_id']&&data.data['app_secret']&&data.data['group_code']){
                            $scope.isAuthorize = 1;
                            $scope.authorize = data.data;
                        }else{
                            $scope.isAuthorize = 0;
                        }
                    } else {
                        notify(data.message, 3);
                        $scope.isAuthorize = 0;
                    }
                }).error(function (data) {
                    notify(data.message, 3);
                });
            }
            requestAuthorize();
            function requestChannel(){
                $http({
                    method:'get',
                    url: '/web-api/publishing/'+$scope.activity_id,
                    headers: JSON.parse($('meta[name="profile"]').attr('content')),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                }).success(function (data) {
                    if (data.code == 200) {
                        $scope.channel = {
                            app: {
                                is_open: data.data.app['is_open']?data.data.app['is_open']:'off',
                                app_urls: data.data.app['app_urls']?data.data.app['app_urls']:[]
                            },
                            wechat: {
                                is_open: data.data.wechat['is_open']?data.data.wechat['is_open']:'off',
                                qr_code: data.data.wechat['qr_code']?data.data.wechat['qr_code']:[]
                            }
                        }
                        $scope.refresh  = true;
                    } else {
                        notify(data.message, 3);
                    }
                }).error(function (data) {
                    notify(data.message, 3);
                });
            }
			@if(!empty($activity->id))
            requestChannel();
			@endif
            function createChannel(callback){
                $http({
                    method:'POST',
                    url: '/web-api/publishing/'+$scope.activity_id,
                    headers: JSON.parse($('meta[name="profile"]').attr('content')),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: $scope.channel
                }).success(function (data) {
                    if (data.code == 200) {
                        callback();
                        // notify(data.message, 2);
                    } else {
                        notify(data.message, 3);
                    }
                }).error(function (data) {
                    notify(data.message, 3);
                });
            }
            $scope.toggleClass = function($event,type){
                if($scope.isAuthorize!=1){
                    bootbox.confirm({
                        title: '提示:',
                        message: "您还未授权公众号，是否现在授权？",
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if(result){
                                ngModal({
                                    templateUrl: '/components/addSubscription.html',
                                    controller: 'subscriptionModalController',
                                    resolve: {
                                        items: function () {
                                            return {
                                                isAuthorize: $scope.isAuthorize,
                                                authorize: $scope.authorize
                                            };
                                        }
                                    },
                                    ok: function (authorize) {
                                        $scope.channel.wechat.is_open = 'on';
                                        $scope.isAuthorize = 1;
                                    },
                                    cancel: function () {

                                    }
                                });
							}
                        }
                    });
                }else{
                    if(type=='label'){
                        if($scope.channel.wechat.is_open=='on'){
                            $scope.channel.wechat.is_open = 'off';
                        }else{
                            $scope.channel.wechat.is_open = 'on';
                        }
                    }else{
                        $scope.channel.wechat.is_open = type;
                    }
                }
            }
            // ================================================
			@if(!empty($activity->id))
                window.groupData ={!! json_encode($activity->group)!!};
            $scope.activity = {
                name: '{{$activity->name}}',
                template: '',
                category: '{{$activity->category}}',
                basic:{!!$basic!!},
                specs:{!! $specs !!},
                prizes:{!! json_encode($activity_pris) !!},
                preview_src: '',
                specs_isopen:{{$specs_isopen}},
                group_isopen:{{$activity->groupIsopen}},//分组是否开启
                group:{!! json_encode($activity->group)!!},
                previewData: {},
                share:{!! $share !!}
            };
            console.log($scope.activity);
            var tpl = $('a[data-template="{{$activity->template_id}}"]').data('detail');
            if (tpl.isBackgroundImage == 1) {
                $('.backgroundImg-container').show();
            } else {
                $('.backgroundImg-container').hide();
            }
            if (tpl.isBackgroundColor == 1) {
                $('.backgroundColor-container').show();
            } else {
                $('.backgroundColor-container').hide();
            }
					@else
            var isBackgroundImage = {{$ativity_template->isBackgroundImage}};
            var isBackgroundColor = {{$ativity_template->isBackgroundColor}};
            var category = $('input[name="category"]').val();

            $scope.activity = {
                name: '',
                template: '',
                category: category,
                basic:{!!$basic!!},
                specs: [],
                prizes: [],
                preview_src: '',
                specs_isopen: 0,
                group_isopen: 0,//分组没有开启
                group: [],//分组没有开启
                previewData: {},
                share: {
                    landindPage: 0
                }
            };


            if (isBackgroundImage == 1) {
                $('.backgroundImg-container').show();
            } else {
                $('.backgroundImg-container').hide();
            }
            if (isBackgroundColor == 1) {
                $('.backgroundColor-container').show();
            } else {
                $('.backgroundColor-container').hide();
            }
            $('#wizardCard').bootstrapWizard('next');

			@endif

					@if(!empty($activity->model_id))
                $scope.activity.previewData = {
                'time': $scope.activity.basic.time,
                'background': '{{$activity->backgroundImg}}'
            }
            $scope.activity.preview_src = "/{{$activity->model->rule}}/activity/preview/{{$activity->model->rule}}/{{$activity->template->template}}"
			@else
                $scope.activity.preview_src = "/{{$ativity_model->rule}}/activity/preview/{{$ativity_model->rule}}/{{$ativity_template->template}}"
			@endif


            /**
             * 选择 活动落地页 或则 自定义落地页
             */
            $scope.selectLandindPage = function (landindPage) {
                if ($scope.activity.share.landindPage == landindPage) {
                    $scope.activity.share.landindPage = 0;
                } else {
                    $scope.activity.share.landindPage = landindPage;
                }
            };
            $scope.previewDataFunc = function () {
                return JSON.stringify($scope.activity.previewData);
            };

            /**
             * @desc 上传活动背景图，试图浏览
             * @param result
             * @param input_name
             */
            window.uploadFilesSuccess = function (result, input_name) {
                if (input_name == 'backgroundImg') {
                    $timeout(function () {
                        console.log($scope.activity);
                        $scope.activity.previewData['background'] = result.url;
                    })
                }
            }

            $scope.$watch('previewDataFunc()', function (newData) {
                if (newData) {
                    newData = JSON.parse(newData);
                    $urlPath = parseURL($scope.activity.preview_src);
                    $scope.activity.preview_src = $urlPath['path'] + '?' + $.param(newData);
                }
            });

            /**
             * @desc 验证数据，并提交
             */
            $scope.onFinishWizard = function () {
                //here you can do something, sent the form to server via ajax and show a success message with swal
                tinyMCE.triggerSave();
                if (valideActivityForm()) {
							@if($ativity_template->template == 'multiple-vote')
								var limit_votes = $.trim($('input[name="limit[votes]"]').val());
								if(!limit_votes){
                                  utils.showNotification('每次最多投多少人不能为空', 3);
								}
								if(limit_votes&&parseInt(limit_votes)<0){
                                    utils.showNotification('每次最多投多少人必须为非负整数',3);
								}
							@endif
                    var obj = $('#activityForm').serialize();
                    $.isLoading({text: '数据提交中，请稍后。。。'});
                    $.post(location.href, obj, function (res) {
                        $.isLoading('hide');
                        if (res.code == 0) {
                            var notify = utils.showNotification('保存成功', 2);
                            setTimeout(function () {
                                notify.close();
                                window.location.href="/web/activity/index";
                            },2000);
                        } else {
                            utils.showNotification(res.message, 3);
                        }
                    });

                }

            }

            /**
             * @desc 是否开启特殊设置
             */
            $scope.openSpec = function () {
                $scope.activity.specs_isopen = $scope.activity.specs_isopen == 1 ? 0 : 1;
            };

            $scope.$on('bootstrap-switch-change', function (event, data) {
                $scope.$apply(function () {
                    if (data.value) {
                        $scope.activity.specs_isopen = 1;
                    } else {
                        $scope.activity.specs_isopen = 0;
                    }
                });

            })

            /**
             * @desc 验证
             * @returns {boolean}
             */
            function valideActivityForm() {
                var form = $('#activityForm');
                var category = $('input[name="category"]').val();
                var url = $('input.app_url').val();
                if (!form.find('input[name=name]').val()) {
                    utils.showNotification('请输入活动名称', 3);
                    return false;
                }
                if (form.find('input[name=name]').val()&&form.find('input[name=name]').val().length>20) {
                    utils.showNotification('活动名称最多不超过20个字符', 3);
                    return false;
                }
                if (!form.find('input[name=startTime]').val()) {
                    utils.showNotification('请输入活动开始时间', 3);
                    return false;
                }
                if (!form.find('input[name=endTime]').val()) {
                    utils.showNotification('请输入活动结束时间', 3);
                    return false;
                }
                if (moment(form.find('input[name=endTime]').val()).unix() < moment(form.find('input[name=startTime]').val()).unix()) {
                    utils.showNotification('活动结束时间不能小于开始时间', 3);
                    return false;
                }
                if (form.find('input[name="limit[num]"]').val() == "") {
                    utils.showNotification('请输入参与活动次数', 3);
                    return false;
                }

                if (typeof valideRuleForm !== 'undefined' && $.isFunction(valideRuleForm)) {
                    var res = valideRuleForm();
                    if (!res) {
                        return false;
                    }
                }
                if ($scope.activity.prizes.length > 0 && $scope.activity.specs_isopen == 1) {
                    var isSuccess = true, errmsg = "";

                    _.each($scope.activity.specs, function (v) {
                        var start = $('input[name="rule[spec][list][' + v.id + '][start]"]').val();
                        var end = $('input[name="rule[spec][list][' + v.id + '][end]"]').val();
                        if (!start) {
                            isSuccess = false;
                            errmsg = "请设置特殊规则的开始时间";
                            return false;
                        }
                        if (!end) {
                            isSuccess = false;
                            errmsg = "请设置特殊规则的结束时间";
                            return false;
                        }
                        if (moment(start).unix() >= moment(end).unix()) {
                            isSuccess = false;
                            errmsg = "特殊规则的开始时间不能大于或等于结束时间";
                            return false;
                        }
                    })
                    if (!isSuccess) {
                        utils.showNotification(errmsg, 3);
                        return false;
                    }
                }
                if($scope.channel.app.is_open=='on'||$scope.channel.app.is_open=='1'){
                    if(!url){
                        utils.showNotification('请输入app下载地址', 3);
                        return false;
                    }
                    if(url&& !/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(url)){
                        utils.showNotification('请输入正确的链接（例如：http://www.chinamcloud.com）', 3);
                        return false;
                    }
                }


                if (category == 1){
                    if (form.find('input[name="share[isopen]"]').is(':checked')){
                        if (!form.find('input[name="share[thumb]"]').val()){
                            utils.showNotification('请上传分享图标',3);
                            return false;
                        }
                        if (!form.find('input[name="share[title]"]').val()){
                            utils.showNotification('请输入分享标题',3);
                            return false;
                        }
                        if (!form.find('textarea[name="share[description]"]').val()){
                            utils.showNotification('请输入分享文案',3);
                            return false;
                        }
                        if (!form.find('input[name="share[qrcode]"]').val()){
                            utils.showNotification('请上传二维码',3);
                            return false;
                        }
                    }
                }else {
                    if ($('#switch-enroll-share').bootstrapSwitch('status') && !$('.input-enroll-self-title').val()) {
                        xx
                        utils.showNotification('请将输入分享标题', 3);
                        return false;
                    }
                    if ($('#switch-enroll-share').bootstrapSwitch('status') && $('.input-enroll-self-title').val().length > 15) {
                        utils.showNotification('分享标题最多为15个字符', 3);
                        return false;
                    }
                    if ($('#switch-enroll-share').bootstrapSwitch('status') && !$('.input-enroll-self-inf').val()) {
                        utils.showNotification('请输入分享文案', 3);
                        return false;
                    }
                    if ($('#switch-enroll-share').bootstrapSwitch('status') && $('.input-enroll-self-inf').val().length > 50) {
                        utils.showNotification('分享文案最多为50个字符', 3);
                        return false;
                    }

                    if (form.find('input[name="share[landindPage]"]:checked').val() == 1){
                        if (!form.find('input[name="share[qrcode]"]').val()){
                            utils.showNotification('请上传底部图片',3);
                            return false;
                        }
                        if (!form.find('input[name="share[download][ios]"]').val()){
                            utils.showNotification('请输入IOS下载地址',3);
                            return false;
                        }
                        if (!form.find('input[name="share[download][android]"]').val()){
                            utils.showNotification('请输入安卓下载地址',3);
                            return false;
                        }
                    }
                    if (form.find('input[name="share[landindPage]"]:checked').val() == 2){
                        if (!form.find('input[name="share[share_url]"]').val()){
                            utils.showNotification('请自定义落地页面地址',3);
                            return false;
                        }
                    }
                }


				@if($ativity_template->template != 'poll' && $ativity_template->template != 'ballot')

                if ($('#bootstrap-vote-table-container').bootstrapTable('getData').length == 0) {
                    if(form.find('input[name="rule[relevanceEnrollOn]"]').is(':checked') != true){
                        utils.showNotification('请将分组和选项设置填写完整再保存！', 3);
                        return false;
                    }
                }
				@endif

                    return true;
            }


            /**
             * 分组设置
             */
            window.saveVoteGroups = []; //保存分组
            $('#switch-vote-group').bootstrapSwitch();
            /**
             * @desc 是否开启分组
             */
            if ($scope.activity.group_isopen) {
                $('#switch-vote-group').bootstrapSwitch('setState', true);
                $('.div-vote-group').css('display', 'block');
            }

            $('#switch-vote-group').on('switch-change', function (e, data) {
                console.log($('.vote-group-card').children('.vote-group-form').length);
                if ($('.vote-group-card').children('.vote-group-form').length != 0 && $scope.activity.group_isopen) {
                    if($('#switch-vote-group').bootstrapSwitch('status') == false){
                        $('#switch-vote-group').bootstrapSwitch('setState', true);
                        utils.showNotification('分组未删除，不可关闭', 3);

                        return false;
                    }
                    return false;
                }else{
                    if (data.value) {
                        $('.div-vote-group').css('display', 'block');
                        $scope.activity.group_isopen = 1;
                    } else {
                        $('.div-vote-group').css('display', 'none');
                        $scope.activity.group_isopen = 0;
                        groupSave();
                    }
                }
            });
//
            /*自定义设置选项卡*/
            $('#switch-enroll-share').bootstrapSwitch();

            if( $scope.activity.share["isopen"] == 'on' ){
                $('#switch-enroll-share').bootstrapSwitch('setState', true);
                $('.div-enroll-self').css('display','block');

                $('.input-enroll-self-title').val($scope.activity.share["title"]);
                $('.input-enroll-self-inf').val($scope.activity.share["content"]);

            }

            $('#switch-enroll-share').on('switch-change', function (e, data) {
                if(data.value){
                    $('.div-enroll-self').css('display','block');
                    $('#switch-enroll-share').bootstrapSwitch('setState', true);

                }else {
                    $('.div-enroll-self').css('display','none');
                    $('#switch-enroll-share').bootstrapSwitch('setState', false);
                }
            });

        }]);
        angular.bootstrap(document, ['app']);
    });


    //初始化添加选项摸态框内容
    function initialAddVote() {
        initUploadImageSize('.vote-upload-smimg');
        $('.vote-display-type-pictuer').click(function () {
            $('.media-video').css('display', 'none');
            $('.media-audio').css('display', 'none');
        });
        $('.vote-display-type-video').click(function () {
            $('.media-video').css('display', 'block');
            $('.media-audio').css('display', 'none');
            initUploadMediaFile('.media-video', 'mp4');
        });
        $('.vote-display-type-audio').click(function () {
            $('.media-video').css('display', 'none');
            $('.media-audio').css('display', 'block');
            initUploadMediaFile('.media-audio', 'mp3');
        });
    }


    /*   选项设置   start  */

    //添加到分组
    $('.add-vote-group-butten').click(function () {
        var addObj = $(this).parent('.add-vote-group');

        var preIndex = addObj.prev('.vote-group-form').data('index');

        var groupHtml = '<li class="card vote-group-form" data-index="' + preIndex + '">' +
            '<div class="content"> ' +
            '<div class="row">' +
            '<div class="col-md-12 col-sm-12">' +
            '<img src="/images/admin/delet_red.png" class="vote_group_card_delet pull-right mgb10 mgr30">' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-md-2 control-label">分组名称</label>' +
            '<div class="col-md-7">' +
            '<input class="form-control" type="text"  placeholder="请输入分组名称" name="group[][name]" data-msg="请输入分组名称" />' +
            '</div></div></div></div></li>';

        addObj.before(groupHtml);
        initialVoteGroup(preIndex);

    });

    $('.vote-group-card').on('click', '.vote_group_card_delet', function () {
        if ($(this).closest('.vote-group-card').children('.vote-group-form').length == 0) {
            return;
        }
        $(this).parents('.vote-group-form').remove();
    });
    //设置选项排序
    $(".vote-group-card").sortable({
        items: "li:not(.add-vote-group)",
        cursor: "move"
    });


    //点击‘选项设置事件’
    $('#voteSet').click(function () {
        $('.groups-tab').remove();
        $('#bootstrap-vote-table-container').before('<ul role="tablist" class="nav nav-tabs groups-tab">' +
            '<li role="presentation"  data-group="all" data-name="" class="active">' +
            '<a data-toggle="tab" aria-expanded="true">全部</a>' +
            '</li>' +
            '</ul>');
        if (window.groupData.length != 0) {
            $('.groups-tab').empty();
            $('.groups-tab').append('<li role="presentation"  data-groupid="all" data-name="" class="active">' +
                '<a data-toggle="tab" aria-expanded="true">全部</a>' +
                '</li>');
//选项中的分组选项卡设置
            window.groupData.forEach(function (val, key) {
                var html = '<li role="presentation"  data-groupid="' + val['group_id'] + '" data-name="' + val['title'] + '">' +
                    '<a data-toggle="tab" aria-expanded="true">' + val['title'] + '</a>' +
                    '</li>';
                $('.groups-tab').append(html);
            });
// $('.groups-tab li:first-child').addClass('active');
// $('#activity_tab_2').children('.card').css('display','block');
        }
    });

    //点击‘选项设置事件 中的分组tab后，保存点击的ID
    window.selectGroupId = 'all';

    //点击选项分组选项卡事件
    $(document).on('click', '.groups-tab li', function () {
// var groupname=$(this).data('name');
        var group_id = $(this).data('groupid');
        $(this).parent().find('li').removeClass('active');
        $(this).addClass('active');

        window.selectGroupId = group_id;

        var activity_id = '{{$activity->id}}';
        if (!activity_id) {
            activity_id = window.activity_demoid;
        } else {
            window.activity_demoid = activity_id;
        }

        refreshSelectOpt(group_id, activity_id);


    });

    //刷新选项设置
    function refreshSelectOpt(group_id, activity_id) {

        $('#bootstrap-vote-table-container').bootstrapTable('refreshOptions', {
            queryParams: function (params) {
                return $.extend(params, {'group_id': group_id, 'activity_id': activity_id});
            },
            onLoadSuccess: function (data) {

                $('.groups-tab').remove();
                $('#bootstrap-vote-table-container').before('<ul role="tablist" class="nav nav-tabs groups-tab">' +
                    '<li role="presentation"  data-group="all" data-name="" class="active">' +
                    '<a data-toggle="tab" aria-expanded="true">全部</a>' +
                    '</li>' +
                    '</ul>');
                if (window.groupData.length != 0) {
                    var active = '';
                    if (group_id == 'all') {
                        active = 'class="active"';
                    }
                    $('.groups-tab').empty();
                    $('.groups-tab').append('<li role="presentation"  data-groupid="all" data-name="" ' + active + '>' +
                        '<a data-toggle="tab" aria-expanded="true">全部</a>' +
                        '</li>');

                    //选项中的分组选项卡设置
                    window.groupData.forEach(function (val, key) {
                        var active = '';
                        if (val['group_id'] == group_id) {
                            active = 'class="active"';
                        }

                        var html = '<li role="presentation"  data-groupid="' + val['group_id'] + '" ' + active + ' data-name="' + val['title'] + '">' +
                            '<a data-toggle="tab" aria-expanded="true">' + val['title'] + '</a>' +
                            '</li>';
                        $('.groups-tab').append(html);
                    });
                }
            }
        })
    }

    function groupSave() {
        var flag = 0;
//        window.groupData = [];

        var tempVoteGroups = [];
        $.extend(tempVoteGroups, window.groupData);

        var groupData = [];
        $('.vote-group-form').each(function () {
            if (!$(this).find('input').val()) {
                flag = 1;
                window.groupData = tempVoteGroups;
                return false;
            }
            groupData.push({'title': $(this).find('input').val(), 'group_id': $(this).data('groupid')});

        })

        if (flag == 0) {
            flag = 1;
            var url = '/web/vote/group';
            var activity_id = '{{$activity->id}}';
            if (!activity_id) {
                activity_id = window.activity_demoid;
            } else {
                window.activity_demoid = activity_id;
            }

            var data = {'data': JSON.stringify(groupData), 'activity_id': activity_id};
            $.isLoading({text: '数据提交中，请稍后。。。'});
            $.post(url, data, function (res) {
                $.isLoading('hide');
                flag = 0;
                if (res.code == 0) {
                    window.groupData = res.data;
                    $("#activity_demoid").val(res.activity_id);
                    window.activity_demoid = res.activity_id;
                    utils.showNotification('分组设值保存成功', 2);
                } else {
                    utils.showNotification('保存失败', 3);
                }
            });
        } else {
            utils.showNotification('请将分组信息填写完整或删除不需要的分组', 3);
        }
    }

    //保存分组
    $('.save-vote-group-butten').click(groupSave);
    $(".vote-group-card").disableSelection();

    //分组设置索引
    function initialVoteGroup(preIndex) {
        var obj = $(".vote-group-form[data-index=" + preIndex + "]").next();
        var optIndex = preIndex + 1;
        obj.attr('data-index', optIndex);
    }


    /*列表配置*/
    initUploadImageSize('.list-sm-images');
    /*选项设置*/
    var vote_table_option = {
        toolbar: ".toolbar",
        search: false,
        searchAlign: 'left',
        buttonsAlign: 'right',
        toolbarAlign: 'right',
        sortOrder: 'desc',
        locale: 'zh-CN',
        idField: 'id',
        icons: {
            refresh: 'fa fa-refresh',
            toggle: 'fa fa-th-list',
            columns: 'fa fa-columns',
            detailOpen: 'fa fa-plus-circle',
            detailClose: 'fa fa-minus-circle',
        },
        sidePagination: 'client',
        /*
         data:[{
         "id": 0,
         "smpicture":"/images/admin/trigger_icon2.png",
         "name": "Item 0",
         "isCheck": 1,
         "category":"test1",
         "displayCategory":"video",
         "vidosrc":"/admin/videotest.mp4",
         "describe":"test",
         "introduction":"jkj8io"
         },{
         "id": 1,
         "smpicture":"/images/admin/did.png",
         "name": "Item 1",
         "isCheck": 0,
         "category":"test1",
         "displayCategory":"video",
         "vidosrc":"/admin/videotest.mp4",
         "describe":"test",
         "introduction":"676876879"
         },{
         "id": 2,
         "smpicture":"/images/admin/did.png",
         "name": "Item 2",
         "isCheck": 1,
         "category":"test1",
         "displayCategory":"audio",
         "audiosrc":"/admin/audio.mp3",
         "describe":"test",
         "introduction":"1233435"
         },{
         "id": 3,
         "smpicture":"/images/admin/did.png",
         "name": "Item 3",
         "isCheck": 0,
         "category":"test1",
         "displayCategory":"audio",
         "audiosrc":"/admin/audiotest.mp3",
         "describe":"test",
         "introduction":"676868i"
         }
         ]
         */
    };
    // var vote_table_options = $.extend({},default_table_option,vote_table_option);

    $('#bootstrap-vote-table-container').bootstrapTable(vote_table_option);
    $('#bootstrap-vote-table-container').on('post-body.bs.table', function () {
        $('[rel="tooltip"]').tooltip();
    });

    function imgFormatter(value, row) {
        var str = '';
        if (row.cover_url != '') {
            str = '<img src="' + row.cover_url + '" class="img-responsive img-rounded"/>'
        }
        return str;
    }

    function codeFormatter(value, row) {
        if (row.code) {
            return row.code;
        }
        return "--";
    }

    function operateFormatter(value, row, index) {
        var dropdown_id = 'dropdown_' + new Date().getTime();
        var actions = [];
        if (row.deleted_at != null) {
            actions.push('<a rel="tooltip" title="已删除" class="btn btn-simple btn-info btn-icon table-action vote-check" href="javascript:void(0)">删除</a>');
        } else {
            actions.push('<a rel="tooltip" title="⃣删除" class="btn btn-simple btn-info btn-icon table-action vote-check" href="javascript:void(0)">删除</a>');
        }
        actions.push([
            '<a rel="tooltip" title="编辑" class="btn btn-simple btn-warning btn-icon table-action vote-set" href="javascript:void(0)">',
            '编辑',
            '</a>',
            '<a rel="tooltip" title="查看" class="btn btn-simple btn-warning btn-icon table-action vote-view" href="javascript:void(0)">',
            '查看',
            '</a>'
        ].join(''));
        if (row.status == 1) {
            actions.push('<a rel="tooltip" title="上架" class="btn btn-simple btn-info btn-icon table-action vote-shelves-on" href="javascript:void(0)">上架</a>');
        } else {
            actions.push('<a rel="tooltip" title="下架" class="btn btn-simple btn-info btn-icon table-action vote-shelves-off" href="javascript:void(0)">下架</a>');
        }
        return actions.join('');
    }
    function statusFormatter(value,row) {
        var status;
        if(row.status == {{App\Models\VoteCandidate\VoteCandidate::SHELVES_ON}}){
            status = '上架';
        }else if(row.status == {{App\Models\VoteCandidate\VoteCandidate::SHELVES_OFF}}){
            status = '下架';
        }
        return status;
    }


    //更新选手
    window.operateEvents = {
        'click .vote-check': function (e, value, row, index) {
            var rowid = row.id;
//            alert(JSON.stringify(row));
            var deleted_at = row.deleted_at == null ? 1 : 0;
            var deleteUrl = '';

            utils.showConfirm('确认删除吗？', 3, function () {

                $.post('/web/vote/delete', {id: row.id, deleted_at: deleted_at}, function (res) {
                    if (res.code == 0) {
                        utils.showNotification(res.message, 2);
                        $('#bootstrap-vote-table-container').bootstrapTable('refresh');
                    } else {
                        utils.showNotification('操作失败', 3);
                    }
                })
                row.deleted_at = deleted_at;
                $('#bootstrap-vote-table-container').bootstrapTable('updateRow', {index: index, row: row});
            });
        },
        'click .vote-shelves-on': function (e, value, row, index) {
            utils.showConfirm('确认上架吗？', 3, function () {
                var shelves_on = "{{App\Models\VoteCandidate\VoteCandidate::SHELVES_ON}}";
                $.post('/web/vote/shelves-edit', {id: row.id, status: shelves_on}, function (res) {
                    if (res.code == 0) {
                        utils.showNotification(res.message, 2);
                        $('#bootstrap-vote-table-container').bootstrapTable('refresh');
                    } else {
                        utils.showNotification('操作失败', 3);
                    }
                })
            });
        },
        'click .vote-shelves-off': function (e, value, row, index) {
            utils.showConfirm('确认下架吗？', 3, function () {
                var shelves_off = "{{App\Models\VoteCandidate\VoteCandidate::SHELVES_OFF}}";
                $.post('/web/vote/shelves-edit', {id: row.id, status: shelves_off}, function (res) {
                    if (res.code == 0) {
                        utils.showNotification(res.message, 2);
                        $('#bootstrap-vote-table-container').bootstrapTable('refresh');
                    } else {
                        utils.showNotification('操作失败', 3);
                    }
                })
            });
        },
        'click .vote-view': function (e, value, row) {
            var viewModal = utils.modal('查看选项', function (ele) {

                var optionCategory = '无分组';
                $.each(window.groupData, function (index, v) {
                    if (row.group_id == v.group_id) {
                        optionCategory = v.title;
                    }
                });

                var optionName = row.title;
                var displayCategory = row.displayCategory;
                var imgSrc = row.cover_url;
                var display = '', displayTitle = '展示内容';
                if(row.from == {{App\Models\Enroll\Enroll::FROM_OLD_DATA}} || row.from == {{App\Models\Enroll\Enroll::FROM_ADD}}) {

                    if ({{$VoteCandidate::TYPE_VIDEO}} == row.type)
                    {
                        if (!row.resource_url[0]) {
                            display = '<h3>正在转码中</h3>';
                        } else {
                            display = '<video width="320" height="240" controls="controls"><source src="' + row.resource_url[0] + '" type="video/mp4"></video>';
                        }

                    }
                	else if ( {{$VoteCandidate::TYPE_AUDIO}} == row.type )
                    {
                        if (row.resource_url.length == 0) {
                            display = '正在转码中'
                        } else {
                            display = '<audio controls="controls"><source src="' + row.resource_url[0] + '" type="audio/mp3"></audio>';
                        }
                    }
                	else
                    {
                        displayTitle = '';
                    }
                } else {
                    displayTitle = '';
				}
                var description = row.description;
                if (row.from == {{App\Models\Enroll\Enroll::FROM_ENROLLS_JSON}}) {
                    var contentJson = JSON.parse(row.content);
                    var introduction = joinContent(contentJson);
				}else {
                    var introduction = row.content;
                }
                var html = '<div class="row">' +
                    '<div class="col-md-12 col-sm-12">' +
                    '<form class="form-horizontal">' +
                    '<div class="form-group">' +
                    '<label class="col-md-2 control-label">名称</label>' +
                    '<div class="col-md-7 control-label" style="text-align: left">' +
                    optionName +
                    '</div>' +
                    '</div>' +
						@if($ativity_template->template != 'poll' && $ativity_template->template != 'ballot')
                            '<div class="form-group">' +
                    			'<label class="col-md-2 control-label">组别</label>' +
                    			'<div class="col-md-7 control-label" style="text-align: left">' +
                    				optionCategory +
                    			'</div>' +
                    		'</div>' +
						@endif
                    '<div class="form-group">' +
                    '<label class="col-md-2 control-label">缩略图</label>' +
                    '<div class="col-md-7" >' +
                    '<div class="vote-view-smimg">' +
                    '<img src="' + imgSrc + '" class="img-responsive">' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="col-md-2 control-label">' + displayTitle + '</label>' +
                    '<div class="col-md-7" >' +
                    display +
                    '</div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="col-md-2 control-label">描述</label>' +
                    '<div class="col-md-7 control-label" style="text-align: left">' +
                    description +
                    '</div>' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="col-md-2 control-label">详细介绍</label>' +
                    '<div class="col-md-7 control-label" style="text-align: left">' +
                    introduction +
                    '</div>' +
                    '</div>' +
                    '</form>' +
                    '</div>' +
                    '</div>';
                ele.find('.modal-body').html(html);
            }, ['返回'], function (res) {
                if (res == 1) {
                    viewModal.modal('hide');
                }
            })
        },
        'click .vote-set': function (e, value, row) {
            var viewModal = utils.modal('编辑选项', function (ele) {
                //解决编辑器弹出层文本框不能输入的问题
                $('#myModal').removeAttr('tabindex');
                var url = $("#bootstrap-vote-table-container").attr('data-url');

                var boolTag = false;

                var activity_id = '{{$activity->id}}';
                if (!activity_id) {
                    activity_id = window.activity_demoid;
                } else {
                    window.activity_demoid = activity_id;
                }

// window.location.href = url;
                var addVoteModal = utils.modal('编辑选项', function (ele) {
                    var html = '<div class="row">' +
                        '<div class="col-md-12 col-sm-12">' +
                        '<form id="addVoteForm" class="form-horizontal" method="" action="">' +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">名称</label>' +
                        '<div class="col-md-7" >' +
                        '<input class="form-control addvote-name" type="text" value="' + row.title + '" name="actorName" placeholder="不超过10个字符"  data-msg="名称不得超过10个字符"/>' +
                        '</div>' +
                        '</div>';
					@if($ativity_template->template != 'poll' && $ativity_template->template != 'ballot')
                        html += '<div class="form-group">';
					@else
						html += '<div class="form-group" style="display:none">';
					@endif
                        html += '<label class="col-md-2 control-label">组别</label>' +
                        '<div class="col-md-7" >' +
                        '<select class="form-control addvote-group" name="actorGroup">';
                    if (window.groupData.length == 0) {
                        html = html + '<option selected>暂未添加分组</option>';
                    } else {

                        $.each(window.groupData, function (index, v) {
                            var selected = '';
                            if (row.group_id == v.group_id) {
                                selected = 'selected';
                            }
                            html = html + '<option value="' + v.group_id + '" ' + selected + '>' + v.title + '</option>';
                        });
                    }
                    html += '</select>' +
                        '</div>' +
                        '</div>' ;
                    {{--@endif--}}
                    var select_img = '';
                    var select_video = '';
                    var select_audio = '';
                    var valueVideoId = '';
                    var valueAudioId = '';
                    var valueVideoUrl = '';
                    var valueAudioUrl = '';
                    var shelves_on = '';
                    var shelves_off = '';
                    if ({{$VoteCandidate::TYPE_VIDEO}} == row.type )
                    {
                        select_video = 'checked';
                        valueVideoId = row.resource_id;
                        valueVideoUrl = row.resource_url[0];

//                        $('.media-video').css('display','block');
//                        $('.media-audio').css('display','none');

                    } else if ( {{$VoteCandidate::TYPE_AUDIO}} == row.type )
                    {
                        select_audio = 'checked';
                        valueAudioId = row.resource_id;
                        valueAudioUrl = row.resource_url[0];
//                        $('.media-video').css('display','none');
//                        $('.media-audio').css('display','block');


                    } else {
                        select_img = 'checked';
                    }
                    if ( {{$VoteCandidate::SHELVES_OFF}} == row.status ){
                        shelves_off = 'checked';
                    } else {
                        shelves_on = 'checked';
                    }

                    html = html +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">权重</label>' +
                        '<div class="col-md-7" >' +
                        '<input class="form-control addvote-weight" type="text" value="' + row.weight + '" name="weight" placeholder="请输入正整数"  data-msg="请输入正整数"/>' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">缩略图</label>' +
                        '<div class="col-md-7 vote-upload-smimg" >' +
                        '<input type="hidden" name="activity_id" id="activity_id" value="' + activity_id + '"/>' +
                        '<input type="hidden" name="id" id="actorid" value="' + row.id + '"/>' +
                        '<input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-target="uploadImageFile" data-for="actorBackgroundImg" data-preview-file-type="text" class="form-control" value="' + row.cover_url + '" title="">' +
                        '<input type="hidden" name="actorBackgroundImg"  data-preview="' + row.cover_url + '" value="' + row.cover_url + '">' +
                        '<span class="help-block">*选择展示类型为照片时，使用选项缩略图。</span>' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">状态</label>' +
                        '<div class="col-md-7" >' +
                        '<label class="radio-inline">' +
                        '<input type="radio" name="status" value="{{$VoteCandidate::SHELVES_ON}}" ' + shelves_on + '> 上架' +
                        '</label>' +
                        '<label class="radio-inline">' +
                        '<input type="radio" name="status" value="{{$VoteCandidate::SHELVES_OFF}}" ' + shelves_off + '> 下架' +
                        '</label>' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">展示类型</label>' +
                        '<div class="col-md-7" >' +
                        '<label class="radio-inline">' +
                        '<input type="radio" name="actorType" class="vote-display-type-pictuer" value="{{$VoteCandidate::TYPE_IMAGE}}" ' + select_img + '> 照片' +
                        '</label>' +
                        '<label class="radio-inline">' +
                        '<input type="radio" name="actorType" class="vote-display-type-video" value="{{$VoteCandidate::TYPE_VIDEO}}" ' + select_video + '> 视频' +
                        '</label>' +
                        '<label class="radio-inline">' +
                        '<input type="radio" name="actorType" class="vote-display-type-audio" value="{{$VoteCandidate::TYPE_AUDIO}}" ' + select_audio + '> 音频' +
                        '</label>' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group media-video" style="display: none">' +
                        '<label class="col-md-2 control-label">视频素材</label>' +
                        '<div class="col-md-7" >' +
                        '<input type="file" name="upfile" accept="video/mp4" data-target="uploadMediaFile" data-for="actorVideo" data-preview-file-type="text" class="form-control" value="' + valueVideoUrl + '" title="">' +
                        '<input type="hidden" name="actorVideo"  data-preview="' + valueVideoUrl + '" value="' + valueVideoId + '">' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group media-audio" style="display: none">' +
                        '<label class="col-md-2 control-label">音频素材</label>' +
                        '<div class="col-md-7" >' +
                        '<input type="file" name="upfile" accept="audio/mp3" data-target="uploadMediaFile" data-for="actorAudio" data-preview-file-type="text" class="form-control" value="' + valueAudioUrl + '" title="">' +
                        '<input type="hidden" name="actorAudio"  data-preview="' + valueAudioUrl + '" value="' + valueAudioId + '">' +
                        '</div>' +
                        '</div>' +
                        '<div class="form-group">' +
                        '<label class="col-md-2 control-label">描述</label>' +
                        '<div class="col-md-7" >' +
                        '<input class="form-control vote-desc" value="' + row.description + '" name="actorDescription" type="text" placeholder="不超过20个字符"  data-msg="不得超过20个字符"/>' +
                        '</div>' +
                        '</div>' ;
						if(row.from !=3 ){
                            html = html +
                                '<div class="form-group">' +
                                '<label class="col-md-2 control-label">详细介绍</label>' +
                                '<div class="col-md-7" >' +
                                '<textarea class="form-control tinymceEditor vote-intd"' +
                                'name="actorIntroduce" placeholder="不超过1000个字" maxlength="1000"' +
                                '>' + row.content + '</textarea>' +
                                '</div>'+
                                '</div>';
                        }else{
						   content =  JSON.parse(row.content);
                            for(var key in content.text){
                                html += '<div class="form-group">' +
                                '<label class="col-md-2 control-label">'+key+'</label>' +
                                '<div class="col-md-7">' ;
                                html += '<input class="form-control vote-desc" name="actorIntroduce['+key+']" value="'+content.text[key]+'"/>';
                                html += '</div></div>';
                            }
						}


                        html = html +'</div>' +
                        '</form>' +
                        '</div>' +
                        '</div>';
                    ele.find('.modal-body').html(html);
                    initTinymce();
                    if ( {{$VoteCandidate::TYPE_VIDEO}} == row.type )
                    {
                        $('.media-video').css('display', 'block');
                        initUploadMediaFile('.media-video', 'mp4');

                    }
                    if ( {{$VoteCandidate::TYPE_AUDIO}} == row.type )
                    {
                        $('.media-audio').css('display', 'block');
                        initUploadMediaFile('.media-audio', 'mp3');

                    }
                }, false, function (res) {

                    if (res == 1 && !boolTag) {
                        tinyMCE.triggerSave();
                        var _form = $('#addVoteForm');
                        console.log('edit:===>'+$('#addVoteForm').serialize());
                        var voteName = _form.find('.addvote-name').val();
                        var voteGroup = _form.find('.addvote-group>option:selected').val();
                        var voteSmimg = _form.find('input[name="actorBackgroundImg"]').val();
                        var voteDisplayType = _form.find('input[type="radio"]:checked').val();
                        var voteDisc = _form.find('.vote-desc').val();
                        var activity_id = _form.find('.activity_id').val();
                        var weight = _form.find('.addvote-weight').val();
                        var voteIntdObj = _form.find('.vote-intd');
                        if(voteIntdObj.length > 0 ){
                            var voteIntd = voteIntdObj.val();
                        }
                        function removeTAG(str){
                            return str?str.replace(/<[^>]+>/g, "").replace(/\&nbsp;/g,""):'';
                        }
                        var voteIntd = removeTAG(voteIntdObj.val());
                        if (voteName == '') {
                            utils.showNotification('选项名称不能为空', 3);
                            return false;
                        } else if (voteName.length > 10) {
                            utils.showNotification('选项名称最多为10个字符', 3);
                            return false;
                        } else if (voteGroup == '') {
                            voteGroup = 'all';
//                            utils.showNotification('请添加分组',3);
//                            return false;
                        } else if (voteSmimg == '') {
                            utils.showNotification('请添加缩略图', 3);
                            return false;
                        } else if (voteDisplayType == '{{$VoteCandidate::TYPE_VIDEO}}' && !_form.find('input[name="actorVideo"]').val()) {
                            utils.showNotification('请添加视频', 3);
                            return false;
                        } else if (voteDisplayType == '{{$VoteCandidate::TYPE_AUDIO}}' && !_form.find('input[name="actorAudio"]').val()) {
                            utils.showNotification('请添加音频', 3);
                            return false;
                        } else if (voteDisc == '') {
                            utils.showNotification('描述不能为空', 3);
                            return false;
                        } else if (voteDisc.length > 20) {
                            utils.showNotification('描述内容不能超过20个字符', 3);
                            return false;
                        } else if (row.from !=3 && voteIntd != undefined && !voteIntd) {
                            utils.showNotification('请添加详细介绍', 3);
                            return false;
                        } else if (row.from !=3 && voteIntd && voteIntd.length > 1000) {
                            utils.showNotification('详细介绍不能超过1000个字符', 3);
                            return false;
                        } else if (isNaN(weight)) {
                            utils.showNotification('权重必须为数字', 3);
                            return false;
                        }
                        var data = _form.serialize();
                        var voteaction = _form.attr('action');
                        var url = $("#bootstrap-vote-table-container").attr('data-url');

                        $.isLoading({text: '数据提交中，请稍后。。。'});

                        boolTag = true;
                        $.post(url, data, function (res) {
                            $.isLoading('hide');
                            boolTag = false;
                            if (res.code == 0) {
                                utils.showNotification('保存成功', 2);
                                addVoteModal.modal('hide');

                                refreshSelectOpt(voteGroup, window.activity_demoid);

                            } else {
                                utils.showNotification(res.message, 3);
                            }
                        });
                    }
                })
                initialAddVote();
            }, ['返回'], function (res) {
                if (res == 1) {
                    viewModal.modal('hide');
                }
            })
        },
        'click .vote-recode': function (e, value, row) {

			/*
			 var optionName=row.name;

			 var recodeModal=utils.modal(optionName+'投票记录', function (ele) {
			 var category = $('input[name="category"]').val();
			 var html = '<table class="table" id="voteRecodeTable" adta-url=""><thead><tr><th data-field="name">名称</th><th data-field="vote_ip">投票IP</th><th data-field="vote_time">投票时间</th></tr></thead></table>';
			 ele.find('.modal-body').html(html);
			 var table_option = {
			 pagination:false,
			 showRefresh:false,
			 search: false,
			 data:[{
			 "id": 0,
			 "name": "Item 0",
			 "vote_ip": 145,
			 "vote_time":"2017-02-24"
			 }, {
			 "id": 1,
			 "name": "Item 1",
			 "vote_ip": 7687,
			 "vote_time":"2017-03-24"
			 }
			 ],
			 queryParams: function (query) {
			 query['candidate_id'] = row.id;
			 // query['exclude'] = exclude;
			 return query;
			 },
			 url: '/web/vote/getRecord'
			 }
			 //                 var recode_table_option = $.extend({},default_table_option, table_option);
			 $('#voteRecodeTable').bootstrapTable(table_option);
			 }, ['返回'], function (res) {
			 if (res == 1) {
			 recodeModal.modal('hide');
			 }
			 })
			 */
        }
    }

    //批量添加
    var $table = $('#bootstrap-vote-table-container');
    var $allCheck = $('#allCheck');
    var selections = [];

    $table.on('check.bs.table uncheck.bs.table ' +
        'check-all.bs.table uncheck-all.bs.table', function () {
        $allCheck.prop('disabled', !$table.bootstrapTable('getSelections').length);
// save your data, here just save the current page
        selections = getIdSelections();
// push or splice the selections if you want to save all data selections
    });

    $allCheck.click(function () {
        var ids = getIdSelections();
        console.log($table.bootstrapTable('getSelections'));

        utils.showConfirm('确认删除吗？', 3, function () {
            var id = JSON.stringify(ids);
            $.get('/web/vote/delete', {id: id}, function (res) {
                if (res.code == 0) {
                    utils.showNotification(res.message, 2);
                    $('#bootstrap-vote-table-container').bootstrapTable('refresh');

                    $.each($table.bootstrapTable('getSelections'), function (key, row) {
                        var rowid = row.id;
                        row.isCheck = 1;
                        $('#bootstrap-vote-table-container').bootstrapTable('updateByUniqueId', {id: rowid, row: row});
                    });
                    $allCheck.prop('disabled', true);
                } else {
                    utils.showNotification('操作失败', 3);
                }
            })
        });
    });
    function getIdSelections() {
        return $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }

    //添加选项
    $('.add-vote-btn').click(function () {
        var url = $(this).attr('data-url');

        var activity_id = '{{$activity->id}}';
        if (!activity_id) {
            activity_id = window.activity_demoid;
        }
        var boolTag = false;
// window.location.href = url;
        var addVoteModal = utils.modal('添加选项', function (ele) {
            var html = '<div class="row">' +
                '<div class="col-md-12 col-sm-12">' +
                '<form id="addVoteForm" class="form-horizontal" method="" action="">' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">名称</label>' +
                '<div class="col-md-7" >' +
                '<input class="form-control addvote-name" type="text" name="actorName" placeholder="不超过10个字符"  data-msg="名称不得超过10个字符"/>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">组别</label>' +
                '<div class="col-md-7" >' +
                '<select class="form-control addvote-group" name="actorGroup">';
            if (window.groupData.length == 0) {
                html = html + '<option selected>暂未添加分组</option>';
            } else {
                $.each(window.groupData, function (index, v) {
                    var selected = '';
                    if (window.selectGroupId == v.group_id) {
                        selected = 'selected';
                    }
                    html = html + '<option value="' + v.group_id + '" ' + selected + ' >' + v.title + '</option>';
                });
            }
            html = html + '</select>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">权重</label>' +
                '<div class="col-md-7" >' +
                '<input class="form-control addvote-weight" type="text" value="0" name="weight" placeholder="请输入正整数"  data-msg="请输入正整数"/>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">缩略图</label>' +
                '<div class="col-md-7 vote-upload-smimg" >' +
                '<input type="hidden" name="activity_id" id="activity_id" value="' + activity_id + '"/>' +
                '<input type="file" name="upfile" accept="image/gif,image/jpeg,image/png" data-target="uploadImageFile" data-for="actorBackgroundImg" data-preview-file-type="text" class="form-control" value="" title="">' +
                '<input type="hidden" name="actorBackgroundImg"  data-preview="" value="">' +
                '<span class="help-block">*选择展示类型为照片时，使用选项缩略图。</span>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">状态</label>' +
                '<div class="col-md-7" >' +
                '<label class="radio-inline">' +
                '<input type="radio" name="status" value="{{$VoteCandidate::SHELVES_ON}}" checked> 上架' +
                '</label>' +
                '<label class="radio-inline">' +
                '<input type="radio" name="status" value="{{$VoteCandidate::SHELVES_OFF}}"> 下架' +
                '</label>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">展示类型</label>' +
                '<div class="col-md-7" >' +
                '<label class="radio-inline">' +
                '<input type="radio" name="actorType" class="vote-display-type-pictuer" value="{{$VoteCandidate::TYPE_IMAGE}}" checked> 照片' +
                '</label>' +
                '<label class="radio-inline">' +
                '<input type="radio" name="actorType" class="vote-display-type-video" value="{{$VoteCandidate::TYPE_VIDEO}}"> 视频' +
                '</label>' +
                '<label class="radio-inline">' +
                '<input type="radio" name="actorType" class="vote-display-type-audio" value="{{$VoteCandidate::TYPE_AUDIO}}"> 音频' +
                '</label>' +
                '</div>' +
                '</div>' +
                '<div class="form-group media-video" style="display: none">' +
                '<label class="col-md-2 control-label">视频素材</label>' +
                '<div class="col-md-7" >' +
                '<input type="file" name="upfile" accept="video/mp4" data-target="uploadMediaFile" data-for="actorVideo" data-preview-file-type="text" class="form-control" value="" title="">' +
                '<input type="hidden" name="actorVideo"  data-preview="" value="">' +
                '</div>' +
                '</div>' +
                '<div class="form-group media-audio" style="display: none">' +
                '<label class="col-md-2 control-label">音频素材</label>' +
                '<div class="col-md-7" >' +
                '<input type="file" name="upfile" accept="audio/mp3" data-target="uploadMediaFile" data-for="actorAudio" data-preview-file-type="text" class="form-control" value="" title="">' +
                '<input type="hidden" name="actorAudio"  data-preview="" value="">' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">描述</label>' +
                '<div class="col-md-7" >' +
                '<input class="form-control vote-desc" name="actorDescription" type="text" placeholder="不超过20个字符"  data-msg="不得超过20个字符"/>' +
                '</div>' +
                '</div>' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label">详细介绍</label>' +
                '<div class="col-md-7" >' +
                '<textarea class="form-control tinymceEditor vote-intd"' +
                'name="actorIntroduce" placeholder="不超过1000个字" maxlength="1000" /></textarea>' +
                '</div>' +
                '</div>' +
                '</form>' +
                '</div>' +
                '</div>';
            ele.find('.modal-body').html(html);
            initTinymce();
            $('#myModal').removeAttr('tabindex');
        }, false, function (res) {
            //解决编辑器弹出层文本框不能输入的问题
            $('#myModal').removeAttr('tabindex');
            if (res == 1 && !boolTag) {
                tinyMCE.triggerSave();
                var _form = $('#addVoteForm');
                console.log($('#addVoteForm').serialize());
                var voteName = _form.find('.addvote-name').val();
                var voteGroup = _form.find('.addvote-group>option:selected').val();
                var voteSmimg = _form.find('input[name="actorBackgroundImg"]').val();
                var voteDisplayType = _form.find('input[type="radio"]:checked').val();
                var voteDisc = _form.find('.vote-desc').val();
                var voteIntd = _form.find('.vote-intd').val();
                var activity_id = _form.find('.activity_id').val();
                var weight = _form.find('.addvote-weight').val();

                if (voteName == '') {
                    utils.showNotification('选项名称不能为空', 3);
                    return false;
                } else if (voteName.length > 10) {
                    utils.showNotification('选项名称最多为10个字符', 3);
                    return false;
                } else if (voteGroup == '') {
                    //刷新所有分组内的候选者
                    voteGroup = 'all';
//                    utils.showNotification('请添加分组',3);
//                    return false;
                } else if (voteSmimg == '') {
                    utils.showNotification('请添加缩略图', 3);
                    return false;
                } else if (voteDisplayType == '{{$VoteCandidate::TYPE_VIDEO}}' && !_form.find('input[name="actorVideo"]').val()) {
                    utils.showNotification('请添加视频', 3);
                    return false;
                } else if (voteDisplayType == '{{$VoteCandidate::TYPE_AUDIO}}' && !_form.find('input[name="actorAudio"]').val()) {
                    utils.showNotification('请添加音频', 3);
                    return false;
                } else if (voteDisc == '') {
                    utils.showNotification('描述不能为空', 3);
                    return false;
                } else if (voteDisc.length > 20) {
                    utils.showNotification('描述内容不能超过20个字符', 3);
                    return false;
                } else if (voteIntd == '') {
                    utils.showNotification('请添加详细介绍', 3);
                    return false;
                } else if (voteIntd.length > 1000) {
                    utils.showNotification('详细介绍不能超过1000个字符', 3);
                    return false;
                } else if (isNaN(weight)) {
                    utils.showNotification('权重必须为数字', 3);
                    return false;
                }
                var data = _form.serialize();
                var voteaction = _form.attr('action');
                var url = $("#bootstrap-vote-table-container").attr('data-url');
                ;

                $.isLoading({text: '数据提交中，请稍后。。。'});

                boolTag = true;
                $.post(url, data, function (res) {
                    $.isLoading('hide');
                    boolTag = false;
                    $("#activity_demoid").val(res.activity_id);
                    window.activity_demoid = res.activity_id;

                    if (res.code == 0) {
                        utils.showNotification('保存成功', 2);
                        addVoteModal.modal('hide');

                        refreshSelectOpt(voteGroup, window.activity_demoid);
                    } else {
                        utils.showNotification('保存失败', 3);
                    }
                });
            }
        })
        initialAddVote();
    });
    /*   选项设置   end */

    //拼接content
    function joinContent(data){
        var html = '';
        for(var key in data['text']){
            html += '<p>'+key+':'+data['text'][key]+'</p>';
        }
        if(data['video']) {
            for (var i=0,l= data['video'].length;i<l;i++) {
                html += '<div>' +
                    '		<video controls poster="' + data.video[i]['cover_url'] + '">' +
                    '		   <source src="' + data.video[i]['resource_url'] + '" type="video/mp4">' +
                    '				您的浏览器不能使用最新的视频播放方式呢' +
                    '       </video>' +
                    '    </div>';
            }
        }
        if (data['img']) {
            for (var j=0,l= data['img'].length;j<l;j++) {
                html += '<div>' +
                    '	    <img src="' + data.img[j] + '" alt="">' +
                    '    </div>';
            }
        }
        return html;
    }
    function initUploadMediaFile(id, type) {
        var container = $('body');
        if (id) {
            container = $(id);
        }
        var uploadFiles = container.find('input[data-target="uploadMediaFile"]');
        $.each(uploadFiles, function (i, v) {
            $_self = $(v);
            var initialPreview = [];
            var initialPreviewConfig = [];
            var previewImage = $('input[name="' + $_self.attr('data-for') + '"]').attr('data-preview') || $('input[name="' + $_self.attr('data-for') + '"]').val();

            if (previewImage) {
                initialPreview.push(previewImage);
                initialPreviewConfig.push({key: getFileName(previewImage)})
            }

            $_self.fileinput({
                allowedFileTypes: ['video', 'audio'],
                language: 'zh',
                initialPreview: initialPreview,
                initialPreviewConfig: initialPreviewConfig,
                showPreview: false,
                deleteUrl: '',
// initialPreviewAsData: true,
                multiple: false,
                allowedFileExtensions: ["'" + type + "'"],
                uploadUrl: "/api/vms/upload",
                overwriteInitial: true,
                dropZoneEnabled: false,
                uploadAsync: true
            })
                .on('fileuploaded', function (event, data, previewId, index) {
                    $.isLoading('hide');
                    if (data.response.code == 0) {
//                    alert(JSON.stringify(data));
                        if (typeof window.uploadFilesSuccess !== 'undefined') {
                            window.uploadFilesSuccess(data.response.id, $(event.target).attr('data-for'));
                        }
//                    $('#'+previewId).attr('data-code',getFileName(data.response.result.attachment));
//                    $('input[name="'+$(event.target).attr('data-for')+'"]').val(data.response.result.original);
                        $('#' + previewId).attr('data-code', getFileName(data.response.id));
                        $('input[name="' + $(event.target).attr('data-for') + '"]').val(data.response.id);
                    } else {
                        utils.showNotification('上传文件失败', 3);
                    }

                }).on('filecleared', function (event) {
                console.log(event, 1);
                $('input[name="' + $(event.target).attr('data-for') + '"]').val('');
            }).on('filedeleted', function (event, key) {
//console.log(event,key,2);
                $('input[name="' + $(event.target).attr('data-for') + '"]').val('');
            }).on('filereset', function (event) {
// console.log(event,3);
                $('input[name="' + $(event.target).attr('data-for') + '"]').val('');
            }).on('filepreupload', function (event) {
// console.log(event,3);//开始提交
                $.isLoading({text: '数据提交中，请稍后。。。'});
            }).on('filesuccessremove', function (event, id) {
                $('input[name="' + $(event.target).attr('data-for') + '"]').val('');
            });
        })
    }
    /*关联报名活动switch按钮事件*/


    $('#switch-vote-enroll').bootstrapSwitch();

    var currModel = {!! $activity->rule !!};

    if(currModel.relevanceEnrollOn=='on'){

        $('#switch-vote-enroll').bootstrapSwitch('setState', true);
        relevanceEnroll();

        $('.div-vote-enroll').css('display', 'block');
    }

    $('#switch-vote-enroll').on('switch-change', function (e, data) {

        if (data.value) {

            relevanceEnroll();

            $('.div-vote-enroll').css('display', 'block');
        } else {
            $('.div-vote-enroll').css('display', 'none');
        }
    });

    function relevanceEnroll() {

        var currModel = {!! $activity->rule !!};

//获取报名列表
        $.get('/web/activity/ajax', {'currModelId':currModel.relevanceEnroll}, function (res) {
            if (res.code == 0) {
                var html= '';
                html+= '<option value="" selected >选择需关联的报名活动</option>';

                $.each( res.data, function(index, content)
                {
                    var selected = '';
                    if(content.selected){
                        selected = ' selected="selected" ';
                    }
                    html+= '<option value="'+content.activity_id+'" '+selected+'>'+content.name+'</option>';

                });

                $('#relevanceEnroll').html(html);
            } else {

            }
        })

    }
</script>
{{--<script src="/js/admin/main.js"></script>--}}
{{--<script src="/js/views/activity/initUploadMediaFile.js"></script>--}}
{{--<script src="/js/views/activity/initialVoteAct.js"></script>--}}
